package redis

import (
	"errors"
	"fmt"
	"gin.project.template/config"
	"gin.project.template/global"
	"github.com/go-redis/redis"
	"time"
)

var client *redis.Client

func InitRedis() {
	if client != nil {
		return
	}
	client = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", config.Conf.Redis.Host, config.Conf.Redis.Port),
		Password: config.Conf.Redis.Password,
		DB:       config.Conf.Redis.DB,
		PoolSize: config.Conf.Redis.PoolSize,
	})

	_, err := client.Ping().Result()
	if err != nil {
		global.Logger.Info("redis init fail")
		panic(err)
	}
	global.Logger.Info("redis init success")
}

func Set(key string, value interface{}, expiration int) error {
	if expiration == 0 {
		expiration = -1
	}

	err := client.Set(key, value, time.Duration(expiration)*time.Second).Err()
	if err != nil {
		global.Logger.Info(fmt.Sprintf("redis set fail, key: %s, value: %s, expiration: %d", key, value, expiration))
		return err
	}

	return nil
}

func Get(key string) (string, error) {
	val, err := client.Get(key).Result()
	if !errors.Is(err, redis.Nil) {
		return val, err
	}

	return val, nil
}
